#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time    : 2021/2/21 21:17
# @Author  : cjw
"""文件数据读取: 需要使用第三方包：pyyaml"""
from os.path import exists, join
from yaml import safe_load_all, safe_load
from xlrd import open_workbook
from configparser import ConfigParser


class FileBase:

	def __init__(self, file_path: str):
		if not exists(file_path):
			raise FileNotFoundError(f'找不到文件：{file_path}')
		self._file_path = file_path
		self._data = None


class YmlReader(FileBase):

	def __init__(self, yml_path: str, multi: bool = False):
		"""
		yml文件读取
		:param yml_path: 文件路径
		:param multi: 是否多节读取，yml文件通过'---'符号进行多节处理
		"""
		super(YmlReader, self).__init__(yml_path)
		self._multi = multi

	@property
	def data(self):
		# 第一次获取数据才进行数据的读取
		if not self._data:
			with open(self._file_path, 'rb') as f:
				if self._multi:
					self._data = list(safe_load_all(f))
				else:
					self._data = safe_load(f)
		return self._data


class ExcelReader(FileBase):

	def __init__(self, excel_path: str, sheet: [str, int], excel_title: bool = True):
		"""
		A  B  C
		A1 B1 C1
		A2 B2 C2

		默认含表头获取方式：
		ExcelReader(path, sheet=0).data
		[{A:A1, B: B1, C: C1},{A:A2, B: B2, C: C2}]

		不含表头获取方式：
		ExcelReader(path, 0, False).data
		[[A1, B1, C1], [A2, B2, C2]]
		:param excel_path: excel文件路径
		:param sheet: 需要获取数据的名称或者索引
		:param excel_title: 返回数据是否需要表头，默认需要
		"""
		super(ExcelReader, self).__init__(excel_path)
		self._sheet = sheet
		self._excel_title = excel_title
		self._data = []

	@property
	def data(self):
		if not self._data:
			work_book = open_workbook(self._file_path)
			if not isinstance(self._sheet, (str, int)):
				raise TypeError(f'excel文件的表格：{self._sheet}, 名称类型不正确')
			if isinstance(self._sheet, int):
				sheet_data = work_book.sheet_by_index(self._sheet)
			else:
				sheet_data = work_book.sheet_by_name(self._sheet)

			# 返回数据含标题
			if self._excel_title:
				title = sheet_data.row_values(0)
				for row_num in range(1, sheet_data.nrows):
					# 每一行的表头和列值组成一个字典的元素，加入到返回列表数据中
					self._data.append(dict(zip(title, sheet_data.row_values(row_num))))
			else:
				for row_num in range(1, sheet_data.nrows):
					self._data.append(sheet_data.row_values(row_num))

		return self._data


class INIReader(FileBase):

	def __init__(self, ini_path: str, section: str = 'MYSQL', ):
		"""
		ini文件数据读取
		:param ini_path: ini文件路径
		:param section: 读取ini文件的节，默认值‘MYSQL’
		"""
		super(INIReader, self).__init__(ini_path)
		self._section = section.upper()
		self._data = {}
		self._parser = ConfigParser()

	@property
	def data(self):
		if not self._data:
			self._parser.read(self._file_path, encoding='UTF-8')
			# 获取节中的数据，并组装成字典返回
			for k, v in self._parser.items(self._section):
				# 某些字段转化为整数类型返回
				self._data[k] = int(v) if k in ('port', 'maxsize', 'minsize', 'min', 'max', 'increment') else v
		return self._data


if __name__ == '__main__':
	from setting.setting import YAML_ELEMENT, DATA

	# yml = YmlReader(YAML_ELEMENT['login_page'])
	# print(type(yml.data), yml.data)
	exl = ExcelReader(join(DATA, 'data.xls'), 0, False)
	print(exl.data)
# ini = INIReader('../chapter08/database.ini', 'oracle')
# print(ini.data)
